#include "TCPServer.h"
#include "TCPTaskPool.h"
#if 0
template <typename TCPTASK>
void TCPServer::newTCPTask(int connfd, struct sockaddr_in * client)
{
	TCPTASK * task = new TCPTASK(connfd, client);
	if ( NULL == task )
		TEMP_FAILURE_RETRY(::close(connfd));
	else if ( !pool->addVerify(task))
	{
		// the ::close will be called in destructor
		delete task;
	}
}
#endif

TCPServer::TCPServer(const std::string & name) : BaseServer(name)
{
	listenSocket = NULL;
	pool = NULL;
}

TCPServer::~TCPServer()
{
	if (pool != NULL )
	{
		pool->finally();
		delete pool;
	}
}

bool TCPServer::bind(const in_port_t port)
{
	BaseServer::init();

	listenSocket = new ServerSocket;
	if ( NULL == listenSocket )
		return false;

	if ( !listenSocket->bind(port) )
		return false;

	return true;
}

void TCPServer::listenForeign()
{
	struct sockaddr_in clientaddr;
	int ret = listenSocket->accept(&clientaddr);
	if ( ret >= 0 )
		newTCPTask(ret, &clientaddr);
}

